package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ArticleMapper;
import com.heima.article.service.ArticleFreemarkerService;
import com.heima.article.service.ArticleService;
import com.heima.common.jackson.InitJacksonConfig;
import com.heima.common.redis.CacheService;
import com.heima.model.article.constants.ArticleConstants;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.article.dtos.Articleload;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.article.vos.HotArticleVo;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.mess.ArticleVisitStreamMess;
import com.heima.model.user.Dtos.AllDto;
import com.heima.model.wemedia.dtos.ManageDto;
import com.heima.model.wemedia.vos.ManageVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, ApArticle> implements ArticleService {
    /**
     * 首页数据加载
     *
     * @param type
     * @param articleload
     */
    private final static short MAX_PAGE_SIZE = 50;

    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private ApArticleConfigMapper apArticleConfigMapper;

    @Autowired
    private ApArticleContentMapper apArticleContentMapper;

    @Autowired
    private ArticleFreemarkerService articleFreemarkerService;

    @Autowired
    private InitJacksonConfig initJacksonConfig;

    @Autowired
    private CacheService cacheService;


    /**
     * 更新文章的分值  同时更新缓存中的热点文章数据
     *
     * @param mess
     */
    @Override
    public void updateScore(ArticleVisitStreamMess mess) {



        //1.更新文章的阅读、点赞、收藏、评论的数量
        ApArticle apArticle = updateArticle(mess);
        //2.计算文章的分值
        //数据苦衷的分值
        Integer score1 = computeScore(apArticle);
        Integer score2 = computeScore(mess);
        Integer score = score1 + score2*2;

        //3.替换当前文章对应频道的热点数据
        replaceDataToRedis(apArticle, score, ArticleConstants.HOT_ARTICLE_FIRST_PAGE + apArticle.getChannelId());

        //4.替换推荐对应的热点数据
        replaceDataToRedis(apArticle, score, ArticleConstants.HOT_ARTICLE_FIRST_PAGE + ArticleConstants.DEFAULT_TAG);

    }

    /**
     * 替换数据并且存入到redis
     * @param apArticle
     * @param score
     * @param s
     */
    private void replaceDataToRedis(ApArticle apArticle, Integer score, String s) {
        String articleListStr = cacheService.get(s);
        if (StringUtils.isNotBlank(articleListStr)) {
            List<HotArticleVo> hotArticleVoList = JSON.parseArray(articleListStr, HotArticleVo.class);

            boolean flag = true;

            //如果缓存中存在该文章，只更新分值
            for (HotArticleVo hotArticleVo : hotArticleVoList) {
                if (hotArticleVo.getId().equals(apArticle.getId())) {
                    hotArticleVo.setScore(score);
                    flag = false;
                    break;
                }
            }

            //如果缓存中不存在，查询缓存中分值最小的一条数据，进行分值的比较，如果当前文章的分值大于缓存中的数据，就替换
            if (flag) {
                if (hotArticleVoList.size() >= 30) {
                    hotArticleVoList = hotArticleVoList.stream().sorted(Comparator.comparing(HotArticleVo::getScore).reversed()).collect(Collectors.toList());
                    HotArticleVo lastHot = hotArticleVoList.get(hotArticleVoList.size() - 1);
                    if (lastHot.getScore() < score) {
                        hotArticleVoList.remove(lastHot);
                        HotArticleVo hot = new HotArticleVo();
                        BeanUtils.copyProperties(apArticle, hot);
                        hot.setScore(score);
                        hotArticleVoList.add(hot);
                    }


                } else {
                    HotArticleVo hot = new HotArticleVo();
                    BeanUtils.copyProperties(apArticle, hot);
                    hot.setScore(score);
                    hotArticleVoList.add(hot);
                }
            }
            //缓存到redis
            hotArticleVoList = hotArticleVoList.stream().sorted(Comparator.comparing(HotArticleVo::getScore).reversed()).collect(Collectors.toList());
            cacheService.set(s, JSON.toJSONString(hotArticleVoList));

        }
    }

    /**
     * 更新文章行为数量
     * @param mess
     */
    private ApArticle updateArticle(ArticleVisitStreamMess mess) {
        ApArticle apArticle = getById(mess.getArticleId());
        apArticle.setCollection((apArticle.getCollection()==null?0:apArticle.getCollection())+mess.getCollect());
        apArticle.setComment((apArticle.getComment()==null?0:apArticle.getComment())+mess.getComment());
        apArticle.setLikes((apArticle.getLikes()==null?0:apArticle.getLikes())+mess.getLike());
        apArticle.setViews((apArticle.getViews()==null?0:apArticle.getViews())+mess.getView());
        updateById(apArticle);
        return apArticle;

    }

    /**
     * 计算文章的具体分值
     * @param apArticle
     * @return
     */
    private Integer computeScore(ApArticle apArticle) {
        Integer score = 0;
        if(apArticle.getLikes() != null){
            score += apArticle.getLikes() * ArticleConstants.HOT_ARTICLE_LIKE_WEIGHT;
        }
        if(apArticle.getViews() != null){
            score += apArticle.getViews();
        }
        if(apArticle.getComment() != null){
            score += apArticle.getComment() * ArticleConstants.HOT_ARTICLE_COMMENT_WEIGHT;
        }
        if(apArticle.getCollection() != null){
            score += apArticle.getCollection() * ArticleConstants.HOT_ARTICLE_COLLECTION_WEIGHT;
        }

        return score;
    }

    private Integer computeScore(ArticleVisitStreamMess mess) {
        Integer score = 0;

            score += mess.getLike() * ArticleConstants.HOT_ARTICLE_LIKE_WEIGHT;


            score += mess.getView();


            score += mess.getComment() * ArticleConstants.HOT_ARTICLE_COMMENT_WEIGHT;


            score += mess.getCollect() * ArticleConstants.HOT_ARTICLE_COLLECTION_WEIGHT;


        return score;
    }

    @Override
    public ResponseResult load(Short type, Articleload articleload) {

        //校验参数
        Integer size = articleload.getSize();
        if (size == null || size == 0){
            size = 10;
        }
        size = Math.min(size, MAX_PAGE_SIZE);
        articleload.setSize(size);

        if (!type.equals(ArticleConstants.LOADTYPE_LOAD_MORE) && !type.equals(ArticleConstants.LOADTYPE_LOAD_NEW)){
            type = ArticleConstants.LOADTYPE_LOAD_MORE;
        }

        //文章频道验证
        if (StringUtils.isEmpty(articleload.getTag())){
            articleload.setTag(ArticleConstants.DEFAULT_TAG);
        }

        //时间校验
        if (articleload.getMaxBehotTime()==null){
            articleload.setMaxBehotTime(new Date());
        }
        if (articleload.getMinBehotTime()==null){
            articleload.setMinBehotTime(new Date());
        }

        //查询数据
        List<ApArticle> apArticles = articleMapper.ApArticleList(type, articleload);
        //封装数据并返回
        ResponseResult result = ResponseResult.okResult(apArticles);
        return result;
    }

    @Override
    public ResponseResult load2(Short type,Articleload articleload) {
        String jsonStr = cacheService.get(ArticleConstants.HOT_ARTICLE_FIRST_PAGE + articleload.getTag());
        ResponseResult responseResult = null;
        if(StringUtils.isNotBlank(jsonStr)){
            List<HotArticleVo> hotArticleVoList = JSON.parseArray(jsonStr, HotArticleVo.class);
            responseResult = ResponseResult.okResult(hotArticleVoList);
        }
        return responseResult;
    }


    /**
     * app端数据同步
     * @param dto
     * @return
     */

    @Override
    public ResponseResult saveArticle(ArticleDto dto) {


        //校验数据
        if (dto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        ApArticle apArticle = new ApArticle();
        BeanUtils.copyProperties(dto,apArticle);

        if (dto.getId() == null){
            //id不存在,保存文章 文章配置 文章内容

            //保存文章
            this.save(apArticle);
            //保存配置
            ApArticleConfig apArticleConfig = new ApArticleConfig(apArticle.getId());
            apArticleConfigMapper.insert(apArticleConfig);
            //保存文章内容
            ApArticleContent apArticleContent = new ApArticleContent();
            apArticleContent.setArticleId(apArticle.getId());
            apArticleContent.setContent(dto.getContent());
            apArticleContentMapper.insert(apArticleContent);
        }else {
            //id存在
            //修改文章
            updateById(apArticle);
            //修改文章内容
            ApArticleContent apArticleContent = apArticleContentMapper.selectOne(Wrappers.<ApArticleContent>lambdaQuery().eq(ApArticleContent::getArticleId, dto.getId()));
            if (apArticleContent != null){
                apArticleContent.setContent(dto.getContent());
            }else{
                throw new RuntimeException("id不存在");
            }
            apArticleContentMapper.updateById(apArticleContent);
        }

        //异步调用
        articleFreemarkerService.buildSrtivleToMinio(apArticle,dto.getContent());

        //返回结果  文章的id
        return ResponseResult.okResult(apArticle.getId());
    }

    /**
     * 查询用户信息
     * @param dto
     * @return
     */
    @Override
    public ApArticle selectOne(AllDto dto) {
        if (dto.getArticleId() == null){
           return null;
        }

        ApArticle apArticle = articleMapper.selectOne(Wrappers.<ApArticle>lambdaQuery().eq(ApArticle::getId, dto.getArticleId()));

        return apArticle;
    }

    /**
     * 观看数据更新加一
     * @param message
     */
    @Override
    public void upDateRead(String message) {
        Long id = Long.valueOf(message);
        ApArticle apArticle = articleMapper.selectOne(Wrappers.<ApArticle>lambdaQuery().eq(ApArticle::getId, id));
        Integer views = apArticle.getViews();

        apArticle.setViews(views==null?1:views+1);
        articleMapper.updateById(apArticle);
    }

    /**
     * 点赞数据库数据更新
     * @param map
     */
    @Override
    public void upDateLike(Map<String,Object> map) {

        ApArticle apArticle = articleMapper.selectOne(Wrappers.<ApArticle>lambdaQuery().eq(ApArticle::getId, map.get("id")));
        Integer likes = apArticle.getLikes();

        if ((boolean) map.get("type")){
            apArticle.setLikes(likes==null?1:likes+1);
        }else {
            apArticle.setLikes(likes==null?1:likes-1);
        }
        articleMapper.updateById(apArticle);
    }

    @Override
    public void upDatecollection(Map<String, Object> map) {
        ApArticle apArticle = articleMapper.selectOne(Wrappers.<ApArticle>lambdaQuery().eq(ApArticle::getId, map.get("id")));
        Integer collection = apArticle.getCollection();

        if ((boolean)map.get("type")){
            apArticle.setCollection(collection==null?1:collection+1);
        }else {
            apArticle.setCollection(collection==null?1:collection-1);
        }
        articleMapper.updateById(apArticle);
    }

    /**
     * 获取列表
     *
     * @param dto
     * @return
     */
    @Override
    public PageResponseResult getNewsList(ManageDto dto) {

        IPage page1 = new Page(dto.getPage(),dto.getSize());

//        List<ApArticle> apArticles = this.list(Wrappers.<ApArticle>lambdaQuery()
//                .eq(ApArticle::getAuthorId, dto.getUserId())
//                .between(ApArticle::getCreatedTime, dto.getBeginDate(), dto.getEndDate()));

        IPage page = page(page1, Wrappers.<ApArticle>lambdaQuery()
                .eq(ApArticle::getAuthorId, dto.getUserId())
                .between(ApArticle::getCreatedTime, dto.getBeginDate(), dto.getEndDate()));

        List<ApArticle> apArticles = page.getRecords();

        List<ManageVo> manageVos = new ArrayList<>();
        for (ApArticle apArticle : apArticles) {
            ManageVo manageVo = new ManageVo();
            BeanUtils.copyProperties(apArticle,manageVo);
            manageVo.setComments(apArticle.getComment());
            ApArticleConfig apArticleConfig = apArticleConfigMapper.selectOne(Wrappers.<ApArticleConfig>lambdaQuery().eq(ApArticleConfig::getArticleId, apArticle.getId()));
            manageVo.setIsComment(apArticleConfig.getIsComment());
            manageVos.add(manageVo);
        }

        PageResponseResult pageResponseResult = new PageResponseResult((int)page.getCurrent(),(int)page.getSize(),(int)page.getTotal());
        pageResponseResult.setData(manageVos);

        return pageResponseResult;
    }


}
